<template>
  <div>
    <div class="content-item">
      <el-form :model="addForm"
               ref="addForm"
               :rules="rules"
               inline>
        <el-row>
          <el-col :span="8">
            <el-form-item label="配置名称："
                          prop="name">
              <el-input v-model="addForm.name"
                        style="width: 216px;"
                        size="small"
                        placeholder="请输入配置名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配置单元："
                          prop="unit">
              <el-select v-model="addForm.unit"
                         size="small"
                         placeholder="请选择配置单元">
                <el-option v-for="(item, index) in unitList"
                           :key="index"
                           :label="item"
                           :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用类型："
                          prop="applianceTypeName">
              <el-select v-model="addForm.applianceTypeName"
                         @visible-change="selectChange"
                         @change="importChange"
                         size="small"
                         placeholder="--适用类型--">
                <el-option v-for="item in typeList"
                           :key="item.id"
                           :label="item.value"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="适用年级："
                          prop="applianceGrade">
              <el-select v-model="addForm.applianceGrade"
                         @visible-change="selectChange"
                         @change="importChange"
                         size="small"
                         placeholder="--年级--">
                <el-option label="不限"
                           :value="null"></el-option>
                <el-option v-for="(item, index) in gradeList"
                           :key="index"
                           :label="item"
                           :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="content-item">
      <div v-if="addForm.unit === '班级'">
        <el-input v-model="queryString1"
                  style="width: 200px;margin-bottom: 10px;"
                  placeholder="请输入专业名称"
                  size="small"></el-input>
        <el-button type="primary"
                   size="small"
                   @click="query(1)">搜索</el-button>
        <el-button size="small"
                   @click="add(1)">+添加</el-button>
        <TabList :tabData="tabData1"
                 class="table-header-gray fixTabs"
                 :specCol="specCol1"
                 :columns="columns1"></TabList>
      </div>
      <div v-else>
        <el-input v-model="queryString3"
                  style="width: 200px;margin-bottom: 10px;"
                  placeholder="请输入学生学号或姓名"
                  size="small"></el-input>
        <el-button type="primary"
                   size="small"
                   @click="query(3)">搜索</el-button>
        <el-button size="small"
                   @click="add(3)">+添加</el-button>
        <TabList :tabData="tabData3"
                 class="table-header-gray fixTabs"
                 :specCol="specCol3"
                 :columns="columns3"></TabList>
      </div>
      <p v-if="addForm.unit === '班级'">已选人数【{{checkedNum1}}】</p>
      <p v-else>已选人数【{{checkedNum3}}】</p>
      <p>
        <el-button size="small"
                   @click="$router.go(-1)">返回</el-button>
        <el-button size="small"
                   :loading="loading"
                   type="primary"
                   @click="sure">执行</el-button>
      </p>
    </div>
    <dialog-add1 :dialogShow="dialogShow1"
                 :addForm="addForm"
                 :mianTabData="tabData1"
                 :checkedTabData="checkedTabData1"
                 @handleClose="handleClose"></dialog-add1>
    <dialog-add3 :dialogShow="dialogShow3"
                 @handleClose="handleClose"
                 :addForm="addForm"
                 :checkedTabData="checkedTabData3"
                 :mianTabData="tabData3">
    </dialog-add3>
  </div>
</template>
<script>
import dialogAdd1 from './dialog-add1'
import dialogAdd3 from './dialog-add3'
import {
  dataDictUsingGET,
  addAdjustDormitorySettingUsingPOST
} from '@api/auto'
import {
  _listAllGrade
} from '@api/common'
export default {
  components: {
    dialogAdd1,
    dialogAdd3
  },
  data () {
    return {
      loading: false,
      dialogShow1: false,
      dialogShow3: false,
      queryString1: '',
      queryString3: '',
      checkedTabData1: [],
      checkedTabData3: [],
      unitList: ['班级', '人员'],
      typeList: [],
      gradeList: [],
      rules: {
        name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }, {
          pattern: /^.{1,30}$/, message: '配置名称限制输入30字'
        }],
        unit: [{ required: true, message: '请选择配置单元', trigger: 'change' }],
        applianceTypeName: [{ required: true, message: '请选择适用类型', trigger: 'blur' }]
      },
      addForm: {
        name: '',
        unit: '班级',
        applianceTypeName: '不限',
        applianceGrade: null
      },
      checkedNum1: 0,
      checkedNum3: 0,
      tabData1: [],
      columns1: [
        { label: '院系', prop: 'collegeName' },
        { label: '专业', prop: 'majorName' },
        { label: '年级', prop: 'gradeName' },
        { label: '班级', prop: 'className' },
        { label: '总人数', prop: 'totalStudent' },
        { label: '操作', prop: 'func' }
      ],
      specCol1: [
        { label: '操作',
          prop: 'func',
          tem: `<div slot-scope="scope">
          <el-button type="text" @click="that.$parent.remove(row, 1, 'classId')">移除</el-button>
        </div>` }
      ],
      tabData3: [],
      columns3: [
        { label: '学号', prop: 'sn' },
        { label: '姓名', prop: 'name' },
        { label: '性别', prop: 'gender' },
        { label: '学生类型', prop: 'studentType' },
        { label: '院系', prop: 'collegeName' },
        { label: '专业', prop: 'majorName' },
        { label: '班级', prop: 'className' },
        { label: '操作', prop: 'func' }
      ],
      specCol3: [
        {
          label: '性别',
          prop: 'gender',
          tem: '<span>{{$transSex(gender)}}</span>'
        },
        { label: '操作',
          prop: 'func',
          tem: `<div>
          <el-button type="text" @click="that.$parent.remove(row, 3, 'id')">移除</el-button>
        </div>` }
      ]

    }
  },
  created () {
    dataDictUsingGET('object_oriented').then(res => {
      this.typeList = res.data
      // this.addForm.applianceTypeName = res.data[0].value
    })
    _listAllGrade().then(res => {
      this.gradeList = res.data
    })
  },
  watch: {
    checkedTabData1 () {
      this.checkedNum1 = 0
      this.checkedTabData1.forEach(item => {
        if (item.totalStudent) {
          this.checkedNum1 += item.totalStudent
        }
      })
    },
    checkedTabData3 () {
      this.checkedNum3 = this.checkedTabData3.length
    }
  },
  methods: {
    handleClose () {
      this.dialogShow1 = false
      this.dialogShow3 = false
    },
    selectChange (boo) {
      if (boo) {
        this.$message.warning('此条件改变将会使已选人数列表清空，请慎重选择')
      }
    },
    importChange () {
      this.tabData1 = []
      this.tabData3 = []
      this.checkedTabData1 = []
      this.checkedTabData3 = []
      this.checkedNum1 = 0
      this.checkedNum3 = 0
    },
    // 搜索（根据num确定是哪边的搜索）
    query (num) {
      let arr = []
      this[`checkedTabData${num}`].forEach(item => {
        if (num === 1) {
          if (item.majorName.includes(this[`queryString${num}`])) {
            arr.push(item)
          }
        } else {
          if (item.sn.includes(this[`queryString${num}`]) || item.name.includes(this[`queryString${num}`])) {
            arr.push(item)
          }
        }
      })
      this[`tabData${num}`] = arr
    },
    add (num) {
      this[`dialogShow${num}`] = true
    },
    sure () {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm('是否确认执行配置?', '提示', {
            type: 'warning'
          }).then(() => {
            if ((!this.checkedNum1 && this.addForm.unit === '班级') || (!this.checkedNum3 && this.addForm.unit === '人员')) {
              this.$message.error('已选人数不能为0')
            } else {
              this.loading = true
              let classSettingList = []
              let studentSns = []
              let params = {}
              let addFormTrans = { ...this.addForm, applianceTypeName: this.addForm.applianceTypeName === '不限' ? null : this.addForm.applianceTypeName }
              if (this.addForm.unit === '班级') {
                this.checkedTabData1.forEach(item => {
                  classSettingList.push({
                    classId: item.classId,
                    studentNum: item.totalStudent
                  })
                })

                params = {
                  ...addFormTrans,
                  type: 0,
                  totalStudentNum: this.addForm.unit === '班级' ? this.checkedNum1 : this.checkedNum3,
                  classSettingList
                }
              } else {
                this.checkedTabData3.forEach(item => {
                  studentSns.push(item.sn)
                })
                params = {
                  ...addFormTrans,
                  type: 0,
                  totalStudentNum: this.addForm.unit === '班级' ? this.checkedNum1 : this.checkedNum3,
                  studentSns
                }
              }
              addAdjustDormitorySettingUsingPOST(params).then(res => {
                this.$message.success('操作成功')
                this.$router.go(-1)
                this.loading = false
              }).catch(res => {
                this.loading = false
              })
            }
          }).catch(() => {
            this.$message.info('已取消执行')
          })
        }
      })
    },
    remove (data, num, judgeStr) {
      this.$confirm('确认移除吗？', '提示', {
        type: 'warning'
      }).then(() => {
        let index = this[`tabData${num}`].findIndex(item => {
          return item[judgeStr] === data[judgeStr]
        })
        let index2 = this[`checkedTabData${num}`].findIndex(item => {
          return item[judgeStr] === data[judgeStr]
        })

        this[`tabData${num}`].splice(index, 1)
        this[`checkedTabData${num}`].splice(index2, 1)
      }).catch(() => {
        this.$message.info('已取消移除')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.addForm {
  display: flex;
  justify-content: space-between;
}
.tab-item {
  padding: 10px;
  border: 1px solid #cccccc;
  height: 580px;
  overflow: auto;
  position: relative;
}
.choosed {
  position: absolute;
  bottom: 0px;
  left: 10px;
}
</style>
<style lang="less">
.fixTabs {
  .el-table__body-wrapper {
    max-height: 435px;
    overflow: auto;
    overflow-x: hidden;
  }
}
</style>
